﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.ProjectFileBLL;
using DotNet.Service;
using KingRoad.EPM.ProjectFileEntity;
using KingRoad.EPM.Web.ViewModels;
using KingRoad.EPM.Common.Configuration;
using System.IO;
using KingRoad.EPM.ProjectInfoBLL;

namespace KingRoad.EPM.Web.Areas.Common.Controllers
{

    ///<summary>
    ///类名：公共上传页面
    ///修改记录
    ///
    ///版本V1.0
    ///<author>
    ///<name>作者：ZL</name>
    ///<data>时间：2016.11.16</data>
    ///</author>
    ///</summary>

    public class UploaderFileController : Controller
    {
        private readonly ProjectFile_DirectoryBLL _directoryBLL = new ProjectFile_DirectoryBLL();
        private readonly ProjectFile_FileBLL _fileBLL = new ProjectFile_FileBLL();
        private readonly Common_FileBLL _commonBLL = new Common_FileBLL();
        //
        // GET: /Common/UploaderFile/
        /// <summary>
        /// 上传页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Uploader(string id)
        {
            ViewBag.Path = Settings.Instance.FileServerUrl;
            ViewBag.UploaderOptionID = id;
            return View();
        }
        /// <summary>
        /// 附件列表
        /// </summary>
        /// <returns></returns>
        public ActionResult FileList(int DirevtoryID, string[] Ids, string[] DeleteIds, bool isDelete)
        {
            ViewBag.Path = Settings.Instance.FileServerUrl;//文件服务器地址
            List<FILE_FILEINFO> list = new List<FILE_FILEINFO>();
            if (Ids.Length > 0 && DeleteIds.Length > 0 && Ids[0] != "" && DeleteIds[0] != "")
            {
                string Itemids = Ids[0].ToString();//过滤用ID
                string[] Item = Itemids.TrimStart('[').TrimEnd(']').Split(',');
                int[] BizID = Array.ConvertAll<string, int>(Item, delegate(string Id) { return int.Parse(Id); });
                string delids = DeleteIds[0].ToString();
                string[] del = delids.TrimStart('[').TrimEnd(']').Split(',');
                int[] DELID = Array.ConvertAll<string, int>(del, delegate(string Id) { return int.Parse(Id); });
                list = _fileBLL.GetFilesListByDirevtoryIDAndBizID(UserService.CurrUserInfo.Id, DirevtoryID, BizID, DELID) ?? new List<FILE_FILEINFO>();
            }
            FILE_DIRECTORY dir = _directoryBLL.GetDirById(DirevtoryID) ?? new FILE_DIRECTORY();
            string dirPath = _directoryBLL.GetPathByDirLevel(dir.DIRECTORY_DIRLEVEL + dir.DIRECTORY_ID);
            ViewBag.FileList = list;
            ViewBag.FilePath = dirPath;
            ViewBag.isDelete = isDelete;
            return View();
        }
        /// <summary>
        ///  根据菜单ID和字符串获取目录列表
        /// </summary>
        /// <param name="MoudleID"></param>
        /// <param name="Ids"></param>
        /// <param name="dirWhere"></param>
        /// <returns></returns>
        public ActionResult GetDirectory(string MoudleID, string Ids,string dirWhere)
        {
            int projId = (string.IsNullOrWhiteSpace(UserService.CurrUserInfo.Themes) ? 0 : int.Parse(UserService.CurrUserInfo.Themes));
            List<FILE_DIRECTORY> list = _directoryBLL.GetDirsByProjIdAndMoudleList(projId, MoudleID, Ids, dirWhere);
            return Json(list);
        }
        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            string statuCode = "300";
            string statuMessage = "删除失败，该文件不存在！";
            string filePath = string.Empty;
            //删除文件
            FILE_FILEINFO model = _fileBLL.GetFile(id) ?? new FILE_FILEINFO();
            //删除数据
            if (model != null)
            {
                //if (_commonBLL.DeteleFile(model.FILE_ID))
                //{
                FILE_DIRECTORY dir = _directoryBLL.GetDirById(model.FILE_DIR);
                string dirPath = _directoryBLL.GetPathByDirLevel(dir.DIRECTORY_DIRLEVEL + dir.DIRECTORY_ID);
                filePath = dirPath + "/" + model.FILE_NAME;
                if (_fileBLL.DelFileNet(id, filePath, Settings.Instance.FileServerUrl + "/Home/DelFile"))
                {
                    statuMessage = "删除成功";
                    statuCode = "200";
                }
                //}
            }
            else
            {
                statuCode = "300";
                statuMessage = "删除失败，该文件不存在！";
            }
            return Json(new CallbackStatus
            {
                message = statuMessage,
                statusCode = statuCode
            });

        }

        public string UploadFile(HttpPostedFileBase FileData)
        {
            string state = string.Empty;//1:上传文件类型不正确，2：上传文件大小超过限制，3：出现异常  
            string tempPath = "/Content/images/Instruction";//上传地址                                           todo:需要修改
            string tempType = KingRoad.EPM.Common.Configuration.Settings.Instance.MeasureFileType;//上传文件类型
            int tempSize = KingRoad.EPM.Common.Configuration.Settings.Instance.ReportlibFileSize;//上传文件大小限制
            if (FileData != null)
            {
                try
                {
                    string tempFile = FileData.FileName;
                    //这里做判断后缀名，取全局配置信息
                    string lastStr = tempFile.Substring(tempFile.LastIndexOf('.')).ToLower();

                    string[] tempList = tempType.Split(';');

                    if (!tempList.Contains(lastStr))
                    {
                        state = "1";
                    }
                    else if (FileData.ContentLength > tempSize * 1024 || FileData.ContentLength == 0)
                    {
                        state = "2";
                    }
                    else
                    {
                        string FileName = Guid.NewGuid().ToString() + lastStr;

                        if (!tempPath.EndsWith("/"))
                            tempPath += "/";

                        state = tempPath + FileName;

                        tempPath = Server.MapPath(tempPath);

                        if (!Directory.Exists(tempPath))
                            Directory.CreateDirectory(tempPath);

                        FileData.SaveAs(tempPath + FileName);
                    }
                }
                catch (Exception e)
                {
                    state = "3";
                }
            }
            return state;
        }
        /// <summary>
        /// 保存上传
        /// </summary>
        /// <param name="path"></param>
        /// <param name="filesNames"></param>
        /// <param name="dirId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveFile(string filesNames, int dirId)
        {
            string OutMessage = "保存失败，请重试！";
            string OutStatus = "300";
            List<FILE_FILEINFO> list = new List<FILE_FILEINFO>();
            if (filesNames.Contains(">"))
            {
                int projId = (string.IsNullOrWhiteSpace(UserService.CurrUserInfo.Themes) ? 0 : int.Parse(UserService.CurrUserInfo.Themes));
                string[] names = filesNames.Split('>');
                FILE_FILEINFO file = null;
                string currentUserId = new UserService().GetActionUserInfo().Id;
                for (int i = 0; i < names.Length - 1; i++)
                {
                    file = new FILE_FILEINFO();
                    file.FILE_NAME = names[i];
                    file.FILE_PROJID = projId;
                    file.FILE_DIR = dirId;
                    file.FILE_USERID = currentUserId;
                    file.FILE_TIME = DateTime.Now;
                    list.Add(file);
                }
            }
            string IDs = _fileBLL.AddFilesOutIds(list);
            if (IDs != string.Empty)
            {
                OutMessage = "上传成功";
                OutStatus = "200";
            }
            return Json(new KingRoad.EPM.Web.ViewModels.CallbackStatus
            {
                message = OutMessage,
                statusCode = OutStatus,
                data = IDs
            });
        }
        /// <summary>
        /// 获取文件服务器保存文件地址
        /// </summary>
        /// <param name="id">FILE_DIRECTORY表主键ID</param>
        /// <returns></returns>
        public ActionResult GetFilePath(int id)
        {
            string filePath = string.Empty;
            FILE_DIRECTORY dir = _directoryBLL.GetDirById(id);
            string dirPath = _directoryBLL.GetPathByDirLevel(dir.DIRECTORY_DIRLEVEL + dir.DIRECTORY_ID);
            return Json(dirPath);
        }
    }
}
